/**
 * 功能:送货单 控制器类
 * 开发人员:daniel.yan
 * 创建时间:2012/4/29 14:19:26
 */
package com.towker.frame.controller.sell;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.towker.web.MyRequest;
import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.core.util.StringUtil;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Customs;
import com.towker.frame.model.sell.Delivery;
import com.towker.frame.model.sell.Order;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.service.basicData.CompaniesService;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.SurplusOrderService;
import com.towker.frame.service.sell.DeliveryService;
import com.towker.frame.service.sell.OrderService;
import com.towker.frame.service.sell.RefGoodsService;
import com.towker.frame.service.sell.SellLineService;
import com.towker.frame.service.warehouse.SendBillsService;
import com.towker.frame.share.sys.user.UserShare;

//送货单
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/sell")
public class DeliveryController extends BaseController
{
	private DeliveryService service;
	private DepartmentsService departmentsService;
	private DepotsService depotsService;
	private SendBillsService sendBillsService;
	private OrderService orderService;
	private SellLineService sellLineService;
	private CompaniesService companiesService;
	private CustomsService customsService;
	private SurplusOrderService surplusOrderService;

	//业务对象注入
	public void setDeliveryService(DeliveryService service)
	{
		this.service = service;
	}
	
	public void setDepartmentsService(DepartmentsService departmentsService) {
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService) {
		this.depotsService = depotsService;
	}

	public void setSendBillsService(SendBillsService sendBillsService) {
		this.sendBillsService = sendBillsService;
	}
	
	public void setOrderService(OrderService orderService)
	{
		this.orderService = orderService;
	}
	
	public void setSellLineService(SellLineService sellLineService) {
		this.sellLineService = sellLineService;
	}
	
	public void setCompaniesService(CompaniesService companiesService)
	{
		this.companiesService = companiesService;
	}

	public void setCustomsService(CustomsService customsService) {
		this.customsService = customsService;
	}

	public void setSurplusOrderService(SurplusOrderService surplusOrderService) {
		this.surplusOrderService = surplusOrderService;
	}

	//添加
	@RequestMapping("/addDelivery{viewName}")
	public ModelAndView addDelivery(HttpServletRequest request, HttpServletResponse response, Delivery po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			//List companiesList = companiesService.getList(map);
			//result.addObject("companiesList",companiesList);
			result.addObject("co_code", UserShare.getCurrentUserCoCode(request));
			result.addObject("sell_dep_code", UserShare.getCurrentUserDepCode(request));
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			result.addObject("customCodes", customCodes);
			Integer infoId = req.getInt("order_id", 0);
			if (infoId>0) {
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.DELIVERIE_GOODS.getValue(), infoId);
				result.addObject("refGoods", refGoods);
			}
			result.addObject("sellLines", sellLineService.getList(map));
			result.setViewName("/manage/sell/addDelivery.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				po.setDelivery_sn(service.getNewDeliverySN());
				if (StringUtils.isBlank(po.getOrder_code())) {
					po.setOrder_code(po.getDelivery_sn());
				}
				po.setCreate_time(new Date());
				po.setCreater_code(UserShare.getCurrentUserCode(request));
				po.setCreater_id(new Integer(String.valueOf(UserShare.getCurrentUserId(request))));
				po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
				//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
				service.add(po);
				String goodsInfo = req.getString("goodsInfo");
				List<RefGoods> processRefGoods = processRefGoods(request, RefGoodsType.DELIVERIE_GOODS, po.getId(), goodsInfo);
				//增加已下单数
				for (RefGoods refGoods : processRefGoods) {
					surplusOrderService.addDownOrderAmount(refGoods.getGoods_id(), po.getDepot_code(), po.getCo_code(), refGoods.getAmount(), true);
				}
				writer.write("添加送货单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加送货单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delDelivery")
	public void delDelivery(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		service.delByIds(CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0)));
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updDelivery{viewName}")
	public ModelAndView updDelivery(HttpServletRequest request, HttpServletResponse response, Delivery po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
//			List companiesList = companiesService.getList(map);
//			result.addObject("companiesList",companiesList);
			
			result.addObject("co_code", UserShare.getCurrentUserCoCode(request));
			result.addObject("sell_dep_code", UserShare.getCurrentUserDepCode(request));
			List<Customs> customCodes= customsService.getList(map);
			result.addObject("customCodes", customCodes);
			if (id>0) {
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.DELIVERIE_GOODS.getValue(), new Integer(String.valueOf(id)));
				result.addObject("refGoods", refGoods);
			}
			result.addObject("sellLines", sellLineService.getList(map));
			result.setViewName("/manage/sell/updDelivery.jsp");
		}
		else if ("2".equals(viewName))
		{
			String goodsInfo = req.getString("goodsInfo");
			PrintWriter writer = response.getWriter();
			try
			{
				service.update(po);
				processRefGoods(request, RefGoodsType.DELIVERIE_GOODS, po.getId(), goodsInfo);
				writer.write("修改送货单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改送货单失败！" + e.getCause());
			}
		} 
		/*else if ("3".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			//复制到发货单
			Long id = req.getLong("keyIndex");
			Delivery delivery = service.getById(id);
			delivery.setStatus(1);
			service.update(delivery);
			SendBills sendBill = new SendBills();
			sendBill.setSend_sn(sendBillsService.getNewSendSn());
			sendBill.setCustom_code(delivery.getCustom_code());
			sendBill.setOrder_id(delivery.getOrder_id());
			sendBill.setOrder_sn(delivery.getOrder_code());
			sendBillsService.add(sendBill);
			
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.DELIVERIE_GOODS.getValue(), delivery.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(sendBill.getId());
				refGoods2.setInfo_type(RefGoodsType.SENDBILL_GOODS.getValue());
				refGoodsService.add(refGoods2);
			}
			writer.write("复制到发货单成功！");
		}*/
		return result;
	}

	//获得分页
	@RequestMapping("/getDelivery")
	public ModelAndView getDelivery(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属公司及部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<Delivery> pageModel = service.getPage(page, pageSize, map);
		for(int i=0;i<pageModel.getResult().size();i++){
			String code = pageModel.getResult().get(i).getCustom_code();
			pageModel.getResult().get(i).setCustoms_name(customsService.getCustomName(false, 0, code));
		}
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/sell/getDelivery.jsp");
		return result;
	}
	
	//获得审核通过的订单分页
	@RequestMapping("/getCopyOrder")
	public ModelAndView getOrder(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		map.put("status", "4");
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<Order> pageModel = orderService.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		Map parMap = new HashMap();
		List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
		List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
		List companiesList = companiesService.getList(parMap);
		Map nullMap = new HashMap();
		result.addObject("sellLines", sellLineService.getList(nullMap));
		result.addObject("departList", departList);
		result.addObject("deportList", deportList);
		result.addObject("companiesList",companiesList);
		
		result.addObject("co_code", UserShare.getCurrentUserCoCode(request)+"["+UserShare.getCurrentUserCoName(request)+"]");
		result.addObject("sell_dep_code", UserShare.getCurrentUserDepCode(request));
		
		result.setViewName("/manage/sell/getCopyOrder.jsp");
		return result;
	}
	
	//复制订单数据
	@RequestMapping("/copyOrder")
	public void copyData(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//ModelAndView result = new ModelAndView();
		MyRequest req = new MyRequest(request);
		Date delivery_date = req.getDate("delivery_date");
		String sell_dep_code = req.getString("sell_dep_code");
		String depot_code = req.getString("depot_code");
		String sell_line = req.getString("sell_line");
		String acc_period = req.getString("acc_period");
		String co_code = req.getString("co_code");
		Long[] idArry = CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0));
		for (int i = 0; i < idArry.length; i++) {
			Integer id = idArry[i].intValue();
			Order order = orderService.getById(id);
			order.setStatus(5);
			orderService.update(order);
			Delivery delivery = new Delivery();
			delivery.setSell_dep_code(sell_dep_code);
			delivery.setDepot_code(depot_code);
			delivery.setSell_line(sell_line);
			delivery.setDelivery_sn(service.getNewDeliverySN());
			delivery.setCustom_code(order.getCustom_code());
			delivery.setOrder_id(order.getId());
			delivery.setOrder_code(order.getOrder_sn());
			delivery.setOrder_date(order.getCreate_date());
			delivery.setAcc_period(acc_period);
			delivery.setCo_code(co_code);
			delivery.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
			delivery.setDelivery_date(delivery_date);
			//delivery.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
			service.add(delivery);
			
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.ORDER_GOODS.getValue(), order.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(delivery.getId());
				refGoods2.setInfo_type(RefGoodsType.DELIVERIE_GOODS.getValue());
				refGoodsService.add(refGoods2);
			}
		}
		PrintWriter writer = response.getWriter();
		writer .write("复制订单成功！");
	}
	

	//明细
	@RequestMapping("/getDeliveryById")
	public ModelAndView getDeliveryById(HttpServletRequest request, HttpServletResponse response)
	{
		Delivery po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		po.setCustoms_name(customsService.getCustomName(false, 0, po.getCustom_code()));
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("dep", departmentsService.getByCode(po.getSell_dep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.DELIVERIE_GOODS.getValue(), new Integer(String.valueOf(id)));
		result.addObject("refGoods", refGoods);
		result.setViewName("/manage/sell/getDeliveryById.jsp");
		return result;
	}
}
